<template>
  <div class="app-container">

    <!-- 表头 查询与新增 -->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input placeholder="关键词过滤" v-model="listQuery.orgCode" style="width: 200px;" class="filter-item"
                    @keyup.enter.native="handleFilter"/>
          <el-select v-model="listQuery.validFlag" placeholder="有效标志" clearable class="filter-item" style="width: 150px"
                     @change="handleFilter">
            <el-option v-for="(value, key) in statusOptions" :key="key" :label="value+'('+key+')'" :value="key"/>
          </el-select>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline"
                     @click="handleCreate">新增
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 表格list -->
    <el-row>
      <el-col :span="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          :height="tableHeight"
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" width="80">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>
          <el-table-column label="商家ID" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.orgCode }}
            </template>
          </el-table-column>
          <el-table-column label="商家名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.orgName }}
            </template>
          </el-table-column>
          <el-table-column label="商家描述" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.orgDesc }}
            </template>
          </el-table-column>
          <el-table-column label="商家图片" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              <img v-if="scope.row.orgImg" :src="imgOrgUrl + scope.row.orgImg" style="width: 50px;height: 50px;">
            </template>
          </el-table-column>
          <el-table-column label="排序号" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.sortNo }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.createdTime | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="有效标志" style="width: 10%" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.validFlag | statusFilter">{{ scope.row.validFlag | validFilter}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <pagination v-show="total>0" :total="total"
                :page.sync="listQuery.pageNum"
                :limit.sync="listQuery.pageSize"
                layout="total, sizes, prev, pager, next"
                style="float:right;"
                @pagination="fetchData"/>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商家ID" label-width="105px" prop="orgCode">
              <el-input v-model="temp.orgCode" :disabled="dialogStatus === 'update'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商家名称" label-width="105px" prop="orgName">
              <el-input v-model="temp.orgName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商家描述" label-width="105px" prop="orgDesc">
              <el-input v-model="temp.orgDesc"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序号" label-width="105px" prop="sortNo">
              <el-input v-model.number="temp.sortNo" auto-complete="off"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="有效标志" label-width="105px">
              <el-switch
                v-model="validSwitch"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="dialogStatus === 'update'">
          <el-col :span="12">
            <el-form-item label="商家图像" label-width="105px">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                with-credentials
                name="file"
                :action="uploadUrl()"
                :on-error="uploadError"
                :on-success="uploadSuccess"
                :before-upload="beforeUpload"
                enctype="multipart/form-data">
                <img v-if="temp.orgImg" :src="temp.orgImg" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import SyOrgDictApi from '@/api/manage/syOrgDict';
  import waves from '@/directive/waves'; // Waves directive
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  export default {
    directives: {waves},
    components: {Pagination},
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'gray',
          0: 'danger'
        }
        return statusMap[status]
      },
      validFilter(status) {
        const statusMap = {
          1: '有效',
          0: '作废'
        }
        return statusMap[status]
      },
      timeFilter(time) {
        if (time) {
          return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
        } else {
          return ''
        }
      }
    },
    data() {
      return {
        list: null, //表格对象
        listLoading: true, //表格加载框
        tableHeight: window.innerHeight - 220, //表格高度
        total: 0, //分页总数
        listQuery: { //表格查询对象
          pageNum: 1,
          pageSize: 5,
          query: '',
          validFlag: undefined,
          orgCode: ''
        },
        temp: {}, //编辑框临时变量
        statusOptions: { //有效无效下拉框
          '1': '有效',
          '0': '作废'
        },
        dialogFormVisible: false, //编辑框显示
        dialogStatus: '', //编辑框更新插入状态
        updateImg: false,//图片是否更新
        textMap: { //编辑框标题
          update: '编辑',
          create: '创建'
        },
        rules: { //编辑框校验规则
          orgCode: [{required: true, message: '商家ID不能为空', trigger: 'change'}],
          orgName: [{required: true, message: '商家名称不能为空', trigger: 'change'}],
          sortNo: [
            {required: true, message: '排序号不能为空'},
            {type: 'number', message: '排序号必须为数字值'}
          ]
        },
        tableKey: 0, //表格key
        imgOrgUrl: process.env.BASE_ORG_IMG,
      }
    },
    computed: {
      validSwitch: {
        // getter
        get: function () {
          return this.temp.validFlag === '1'
        },
        // setter
        set: function (newValue) {
          if (newValue) {
            this.temp.validFlag = '1'
          } else {
            this.temp.validFlag = '0'
          }
        }
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      /**
       * 获取表格数据
       */
      fetchData() {
        let that = this;
        this.listLoading = true
        this.$http.all([SyOrgDictApi.getPage(this.listQuery)])
          .then(this.$http.spread(function (perms) {
            that.list = perms.rows
            that.total = perms.total
            that.listLoading = false
          }));
      },
      /**
       * 新增弹窗
       */
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * 清空弹窗内容
       */
      resetTemp() {
        this.temp = {
          orgCode: '',
          orgName: '',
          orgDesc: '',
          orgImg: '',
          orgType: '',
          payMethod: '',
          sortNo: '',
          createdTime: '',
          modifiedTime: '',
          validFlag: '1'
        }
      },
      /**
       * 确定新增
       */
      createData() {
        let that = this;
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            SyOrgDictApi.insert(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData();
                }
              })
            })
          }
        })
      },
      /**
       * 编辑弹窗
       */
      handleUpdate(row) {
        this.temp = Object.assign({}, row)
        if(this.temp.orgImg){
          this.temp.orgImg = this.imgOrgUrl + this.temp.orgImg;
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * 确认编辑
       */
      updateData() {
        let that = this;
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            delete tempData.orgImg
            SyOrgDictApi.update(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  if (that.updateImg) {
                    that.updateImg = false
                    window.location.reload()
                  } else {
                    that.fetchData();
                  }
                }
              })
            })
          }
        })
      },
      /**
       * 删除操作
       */
      handleDelete(row) {
        let that = this;
        SyOrgDictApi.remove({orgCode: row.orgCode}).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 1000,
            onClose() {
              that.fetchData();
            }
          })
        })
      },
      /**
       * 搜索过滤
       */
      handleFilter() {
        this.listQuery.pageNum = 1
        this.fetchData()
      },
      /**
       * 图片上传地址
       */
      uploadUrl() {
        return process.env.BASE_API + '/syOrgDict/update?orgCode=' + this.temp.orgCode;
      },
      /**
       * 上传错误处理
       */
      uploadError() {
        this.$message.error('上传失败，请重新上传')
      },
      /**
       * 上传成功处理
       */
      uploadSuccess(res, file) {
        this.temp.orgImg = URL.createObjectURL(file.raw)
        this.updateImg = true;
        this.$notify({
          title: '成功',
          message: '图片上传成功',
          type: 'success',
          duration: 1000
        })
      },
      /**
       * 上传前置处理
       */
      beforeUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB！')
        }
      },
    }
  }
</script>

<style scoped>
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
